import Vue from 'vue'
import Vuex from 'vuex'

import API from '@/api/api-chat-list.js'
import slidingScrollBar from '@/utils/slidingScrollBar.js'
import getTime from '@/utils/getTime.js'
import {isEmpty} from "../common/util";
import dayjs from "dayjs";
import persistedState from 'vuex-persistedstate'
import { thePartyBranch321 } from "@/store/modules/thePartyBranch321";
import { redBase} from "@/store/modules/redBase";

Vue.use(Vuex)

// 捕获异常 气泡显示的数据
const errorText = {
  data: {
    type: 'text',
    data: '非常抱歉，查询出错了。'
  }
}

const queryUserText = {
  data: {
    type: 'text',
    data: '十分抱歉，暂时未匹配到您的问题，请确认该查询对象是否为党员或公司员工，期待再次为您服务！！'
  }
}

const queryDeptText = {
  data: {
    type: 'text',
    data: '十分抱歉，暂时未匹配到您的问题，请确认该查询对象是否为支部名称，期待再次为您服务！！'
  }
}


const queryUserOrDeptText = {
  data: {
    type: 'text',
    data: '非常抱歉，暂时未匹配到党员或者支部，期待再次为您服务！！'
  }
}

/**
 * 往业务数据中增加自定义数据  搜索排行榜  热点问题
 * @param {*} answersData 接口返回的数据
 * @param {*} name 查询的内容
 * @returns 返回新的数据
 */
function publicQuestionsCode(answersData,name){
  answersData['data'] = {
    type: 'business',
    name: name,
    data: answersData.data
  };
  return answersData;
}

export default new Vuex.Store({
  state: {
    robotInfo: null,   //机器人信息
    userInfo: null,   //用户信息
    workSubTasks: null,   //待办日期列表
    users: null,
    categoryList: null,  //题库类型
    quickNavList: null, //快捷导航
    quickNavListData: null, //快捷导航
    rhPlate: 'ZC',  //当前板块，默认是智查板块
    rhScrollTop: {//用来保留智办页面切换时原页面的ScrollTop值。
      "ZC": 0,
      "ZX": 0,
      "ZB": 0,
      "ZS": 0
    },
    questionsAnswersData: {  //存储4R问答数据
      "ZC": [],
      "ZX": [],
      "ZB": [],
      "ZS": []
    },  //存储问答数据
    categoryListData: null, //存储初始化题库类型数据
    categoryLists: null,  //智学快捷导航
    calendarShow: false,  // 日历展示
    workOrderType: 'workOrderInform',  // 默认展示工单信息
    workApplyData: null, //工单信息
    workApplyParentData: null, //父类工单信息
    taskData: null,
    levelTitleList: null,  //标题列表
    firstTopicData: null,  // 第一议题列表
    firstTopicContent: null,  // 第一议题详细内容
    firstTopicSearchData: {}, // 第一议题搜索框输入内容
    meetingInfoMap: new Map(), // 会议信息
    zxInitCategory: null, // 智学详细信息初始化Category
    zxInitLevel1Title: null, // 智学详细信息初始化一级标题
    imgDisplay: false, // 是否展示党史照片
    chooseDate: dayjs(), // 日历选中的日期
    autoDsImgDisplay: true, // 第一次打开日历自动展示党史图片信息
    timerId: null, // 定时器id
    autoCloseTimer: 5, // 默认为5秒钟不做操作自动关闭
    lastChatTime: null, // 最后一次发送消息的时间
    initChatTimeCount: 4, // 聊天日期四个页面需要初始化
    datePickerShow: true,
  },
  mutations: {
    // 设置机器人信息
    setRobotInfo(state, value) {
      state.robotInfo = value;
    },
    // 设置用户信息
    setUserInfo(state, value) {
      state.userInfo = value;
    },
    setWorkSubTasks(state, value) {
      state.workSubTasks = value;
    },
    // 设置题库信息
    setCategoryList(state, value) {
      state.categoryList = value;
    },
    // 设置题库信息
    setCategoryLists(state, value) {
      state.categoryLists = value;
    },
    // 设置更多栏目信息
    setQuickNavList(state, value) {
      state.quickNavList = value;
    },
    // 当前问答板块
    setRhPlate(state,value){
      state.rhPlate = value;
    },
    // 问答板块的 ScrollTop
    setRhScrollTop(state,value){
      state.rhScrollTop[state.rhPlate] = value;
    },
    // 工单展示板块切换
    setWorkOrderType(state,value){
      state.workOrderType = value;
    },
    // 设置初始化题库列表
    setCategoryListData(state,value){
      state.categoryListData = value;
    },
    // 设置问答数据
    setQuestionsAnswersData(state, params) {
      // 往对应的数组中传入数据
      const msgStr = params?.data?.data;
      state.questionsAnswersData[params.rhPlate ? params.rhPlate : state.rhPlate].push(params);
      Vue.nextTick(() => {
        if (msgStr === '这是您的政治生日!' || params?.data?.type === 'meeting') {
          // 滑动到底部
          slidingScrollBar(null,'smooth');
        } else {
          // 获取当前板块中用户提问元素
          const questionsDomList = document.querySelectorAll('#CON_' + state.rhPlate + ' .questions');
          // 获取最后一个用户提问元素
          const questionsDom = Array.from(questionsDomList)[questionsDomList.length - 1];
          // 获取该元素距离顶部的距离
          const questionsDomOffsetTop = questionsDom ? questionsDom.offsetTop + 20 : 0;
          slidingScrollBar(questionsDomOffsetTop,'smooth');
        }
      })
    },
    // 设置工单基本信息数据
    setWorkApplyData(state, value){
      state.workApplyData = value;
    },
    setWorkApplyParentData(state, value){
      state.workApplyParentData = value;
    },
    // 设置工单任务信息数据
    setTaskData(state, value){
      state.taskData = value;
    },
    // 清理数据
    clearQuestionsAnswersData(state) {
      state.questionsAnswersData[state.rhPlate].splice(1);
    },
    // 将之前设置为空的数据 赋值为查找到的内容
    modifyQuestionsAnswersData(state, params) {
      const {talkSessionId, answersData} = params;
      const value = state.questionsAnswersData[state.rhPlate];
      value?.forEach(item => {
        if (item.type === 'send_search' && item.talkSessionId === talkSessionId) {
          item.data = answersData.data;
        }
      });
    },
    // 点击更多足迹将查询的数据插入到相应的足迹仓库中
    modifyAnswersFootPrintData(state, params) {
      const {talkSessionId, answersData} = params;
      const value = state.questionsAnswersData[state.rhPlate];
      value?.forEach(item => {
        if (item.data.type === 'footPrint' && item.talkSessionId === talkSessionId) {
          item.data.data = answersData;
        }
      });
    },
    // 设置日历展示
    setCalendarShow(state, value) {
      state.calendarShow = value;
    }
  },
  actions: {
    // 通过文本查询
    async asyncGetTalkAnswers(context,params){
      let answersData;
      try{
        answersData = await API.getTalkAnswers(params);
      }catch(error){
        answersData = errorText;
      }
      context.commit('modifyQuestionsAnswersData',{talkSessionId: params.talkSessionId,answersData});
    },

    // 智查搜索栏查询
    async asyncGetQueryUserOrDeptAnswers(context, params) {
      let queryUserResult;
      let queryDeptResult;
      let answersData = {};
      try {
        // 首先查用户
        queryUserResult = await API.queryUsers(params);
        const queryUserData = queryUserResult.data;

        const queryUserDataLength = queryUserData?.length;

        // 根据输入值查到用户,查询到唯一用户
        if (queryUserDataLength === 1) {
          // 封装数据
          queryUserResult.type = "queryUsers";
          answersData.data = queryUserResult;
        } else if(queryUserDataLength > 1){
          // 查询到多个用户
          queryUserResult.type = "queryUsersList";
          answersData.data = queryUserResult;
        }

        // 查用户为空
        if (isEmpty(queryUserResult) || isEmpty(queryUserData)) {

          // 查组织
          queryDeptResult = await API.queryDepts(params);
          const queryDeptData = queryDeptResult.data
          // 查到单个组织数据
          const queryDeptDataLength = queryDeptData?.length;
          if (queryDeptDataLength === 1) {
            // 封装数据
            queryDeptResult.type = "queryDepts";
            answersData.data = queryDeptResult;
          } else if (queryDeptDataLength > 1){
            // 查到多个组织数据集合
            queryDeptResult.type = "queryDeptsList";
            answersData.data = queryDeptResult;
          }

          // 查用户和组织都查不到时给提醒信息
          if (isEmpty(queryDeptResult) || isEmpty(queryDeptData)) {
            answersData = queryUserOrDeptText;
          }
        }
      } catch
        (error) {
        answersData = errorText;
      }
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    }
    ,


    // 通过id查询
    async asyncQueryById(context, params) {
      let answersData;
      try {
        answersData = await API.queryById(params);
      } catch (error) {
        answersData = errorText;
      }
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    }
    ,
    // 通过路径查询
    async asyncQueryByPath(context, params) {
      let answersData;
      try {
        answersData = await API.queryByPath(params);
        if(answersData.data.type === "object" && answersData.data.data.ansContentFileList === undefined){
          answersData.data.data.question = undefined;
        }
      }
       catch (error) {
        answersData = errorText;
      }
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },
    // 查询业务
    async asyncSearchQuestions(context, params) {
      const {talkSessionId} = params;
      let answersData = await API.getSearchQuestions();
      answersData = publicQuestionsCode(answersData, '搜索排行榜');
      context.commit('modifyQuestionsAnswersData', {talkSessionId, answersData});
    },
    async asyncHotQuestions(context, params) {
      const {talkSessionId} = params;
      let answersData = await API.getHotQuestions();
      answersData = publicQuestionsCode(answersData, '热点问题');
      context.commit('modifyQuestionsAnswersData', {talkSessionId, answersData});
    },
    // 查询足迹
    async asyncFootPrint(context, params) {
      const {time, talkSessionId} = params;
      const footPrintData = await API.getFootPrint({time});
      const answersData = footPrintData.data;
      answersData['data'] = {
        type: 'footPrint',
        talkSessionId: params.talkSessionId,
        data: footPrintData.data,
      };
      context.commit('modifyQuestionsAnswersData', {talkSessionId, answersData});
      Vue.nextTick(() => {
        const dom = document.getElementById(talkSessionId);
        dom && dom.setAttribute('footPrint-time', getTime(answersData[answersData.length - 1].createTime));
      });
    }
    ,
    // 查询工单
    async asyncQuestionsAnswersData(context, params) {
      const returnData = await API.queryTaskList(params);
      returnData.type = "workOrderList";
      returnData.workOrderName = params.workOrderName;
      returnData.workOrderType = params.type;
      const answersData = {
        data: returnData
      };
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },

    // 查询用户信息
    async asyncQueryUsers(context, params) {
      const queryUserResult = await API.queryUsers(params);
      const queryUserData = queryUserResult.data;
      let answersData = {};
      if (!isEmpty(queryUserData)) {
        // 封装数据
        queryUserResult.type = "queryUsers";
        answersData.data = queryUserResult;
      }

      // 查用户为空
      if (isEmpty(queryUserResult) || isEmpty(queryUserData)) {
        answersData = queryUserText;
      }

      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },


    // 查询用户党组织信息
    async asyncQueryDepts(context, params) {
      let answersData = {};
      // 参数校验
      const orgName = params.orgName
      if (isEmpty(orgName)) {
        answersData = queryDeptText;
      } else {
        const queryDeptsResult = await API.queryDepts(params);
        const queryDeptsData = queryDeptsResult.data;


        if (!isEmpty(queryDeptsData)) {
          // 封装数据
          queryDeptsResult.type = "queryDepts";
          answersData.data = queryDeptsResult;
        }

        // 查部门为空
        if (isEmpty(queryDeptsResult) || isEmpty(queryDeptsData)) {
          answersData = queryDeptText;
        }
      }

      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },
    // 查询智学导航栏信息
    async asyncQuickNavigation(context, params) {
      this.state.quickNavListData = await API.getTalkAnswers(params);
    },
    // 智能巡查气泡框内容
    async asyncInTellingPatrolInspect(context,params){
      const answersData ={
        data: {
          type: params.type,
          data: null
        }
      };
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },
    // 工单搜索
    async asyncWorkOrderQuestionsAnswersData(context, params) {
      params.type = 'TODO_TASK';
      const toDoTaskList = await API.queryTaskList(params);

      params.type = 'DONE_TASK';
      const doneTaskList = await API.queryTaskList(params);

      params.type = 'MY_APPLICANT';
      const myApplicantTaskList = await API.queryTaskList(params);

      const answersData = {
        data: {
          type: "workOrderSearchList",
          data: {
            toDoTaskList: toDoTaskList,
            doneTaskList: doneTaskList,
            myApplicantTaskList: myApplicantTaskList
          }
        }
      };

      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },
    async asyncSearchZSQuestionsAnswersData(context, params) {
      const ztcList = await API.getZtcLikeByTitle(params.inputValue);
      const answersData = {
        data: {
          type: 'ZSTitleList',
          data: {
            ztcList: ztcList
          }
        }
      }
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    },
    async asyncRoleMsg(context, params) {
      const answersData = {
        data: {
          type: 'roleErrMsg'
        }
      }
      context.commit('modifyQuestionsAnswersData', {talkSessionId: params.talkSessionId, answersData});
    }
  },
  modules: {
    thePartyBranch321, // 党支部312提醒模块
    redBase,
  },
  plugins: [
    persistedState({
      // 默认使用localStorage来存储数据，如果要使用sessionStorage:
      storage: window.sessionStorage,
      // 存储的 key 的key值
      key: "store",
      reducer(val) {
        return {
          // 储存modules中的thePartyBranch321
          thePartyBranch321: val.thePartyBranch321
        }
      }
    })
  ],
})
